package com.thinkfit.jy.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.GsonUtils;
import com.common.lib.activity.BaseActivity;
import com.common.lib.bean.BannerBean;
import com.common.lib.bean.ProceduralTrainBean;
import com.common.lib.bean.UserBean;
import com.common.lib.bean.VersionBean;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.thinkfit.jy.R;
import com.thinkfit.jy.bluetooth.Bluetooth;
import com.thinkfit.jy.contract.MainContract;
import com.thinkfit.jy.dialog.SoundPopupWindow;
import com.thinkfit.jy.fragment.AboutSettingFragment;
import com.thinkfit.jy.fragment.AdminModeFragment;
import com.thinkfit.jy.fragment.ApplicationFragment;
import com.thinkfit.jy.fragment.GeneralSettingFragment;
import com.thinkfit.jy.fragment.HomeDWFragment;
import com.thinkfit.jy.fragment.HomeJyFragment;
import com.thinkfit.jy.fragment.HomeNewFragment;
import com.thinkfit.jy.fragment.HomePinkFragment;
import com.thinkfit.jy.fragment.HomeSceneryFragment;
import com.thinkfit.jy.fragment.HomeXFFragment;
import com.thinkfit.jy.fragment.SportRecordFragment;
import com.thinkfit.jy.fragment.SportsCenterFragment;
import com.thinkfit.jy.fragment.SystemSettingFragment;
import com.thinkfit.jy.fragment.VideoListFragment;
import com.thinkfit.jy.presenter.MainPresenter;
import com.thinkfit.jy.receiver.BluetoothBroadcastReceiver;
import com.thinkfit.jy.receiver.WifiBroadcastReceiver;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.serialport.SportStatus;
import com.thinkfit.jy.serialport.SportType;
import com.thinkfit.jy.utils.ApkListViewUtils;
import com.thinkfit.jy.utils.BackButtonViewUtils;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.CountDownViewUtils;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.DialogViewUtils;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.FastBlurUtility;
import com.thinkfit.jy.utils.LayoutTouchListenerUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.RunningAppUtils;
import com.thinkfit.jy.utils.SafetyLockViewUtils;
import com.thinkfit.jy.utils.SetTargetViewUtils;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.ShowSpeeldAndSlopUtils;
import com.thinkfit.jy.utils.SimpleSettingViewUtils;
import com.thinkfit.jy.utils.SportsDataUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.SystemUtils;
import com.thinkfit.jy.utils.ThemeUtils;
import com.thinkfit.jy.utils.ToastUtils;
import com.thinkfit.jy.utils.Utils;
import com.thinkfit.jy.utils.WifiSupport;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity<MainContract.Presenter> implements MainContract.View {

    private Disposable mDisposableCountDown;
    protected boolean mIsMainActivity = false;
    WifiBroadcastReceiver wifiBroadcastReceiver;
    BluetoothBroadcastReceiver bluetoothBroadcastReceiver;
    int targetType,targetNum;
    boolean isShowToast = true;

    ViewPager viewPager;
    LinearLayout llArea;
    ConstraintLayout llHome,llSportsCenter,llVideoCourse,llEntertainment,llDataHub,llRetract,
            clHome,clSportsCenter,clVideoCourse,clEntertainment,clDataHub,clRetract,clSetItem;
    TextView tvHelp,tvSetting,tvStartSports,tvHome,tvllSportsCenter,tvVideoCourse,tvEntertainment,tvDataHub,tvRetract,
            tvArea,tvLanguage,tvUnit;
    ImageView ivHome,ivllSportsCenter,ivVideoCourse,ivEntertainment,ivDataHub,ivRetract;

    int mCurrentItem;
    private ArrayList<BaseFragment> mFragments;
    private ArrayList<TextView> textViews;
    private ArrayList<ImageView> imageViews;
    private ArrayList<ConstraintLayout> clViews;
    private ArrayList<ConstraintLayout> clAnimationViews;

    FragmentTransaction fragmentTransaction;
    boolean isStartPlay = true;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreated(@Nullable Bundle savedInstanceState) {
        sendWifiBroadcastReceiver();
        sendBluetoothBroadcastReceiver();
        init();
    }

    public void onResume() {
        super.onResume();
//        showUserInfo();
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        showBottomUI();
        DataManager.Companion.getInstance().setObject(null);
        //TODO 临时try，界面来不及统一
        try {
            setImage(R.id.iv_wifi, WifiSupport.isWifiConnected(getContext()) ? R.drawable.img_main_wifi:
                    R.drawable.img_main_wifi_back);
        }catch (Exception e){
            e.printStackTrace();
        }
        SerialPortManager.getInstance();
        SportsStatusBarViewUtils.getInstance().goneLayout();
        ShowSpeedViewUtils.getInstance().goneLayout();
        initSound();

    }

    @Override
    protected void onStart() {
        super.onStart();
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    currentVolume : "+currentVolume);
        SportsStatusBarViewUtils.getInstance().setVolume(currentVolume);
    }

    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("ddddddddddddddddddddddd MainActivity  onStop");

        DeviceTypeUtils.showBackButton(getApplicationContext());
    }

    public void sendWifiBroadcastReceiver(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        intentFilter.addAction("android.net.wifi.STATE_CHANGE");
        intentFilter.addAction("android.net.wifi.SCAN_RESULTS");
        intentFilter.addAction("android.net.wifi.supplicant.STATE_CHANGE");
        wifiBroadcastReceiver = new WifiBroadcastReceiver();
        registerReceiver(wifiBroadcastReceiver, intentFilter);

        Intent intent = new Intent();
        intent.setAction("android.net.wifi.WIFI_STATE_CHANGED");
        intent.setFlags(0x01000000);
        sendBroadcast(intent);
    }

    public void sendBluetoothBroadcastReceiver(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        bluetoothBroadcastReceiver = new BluetoothBroadcastReceiver();
        registerReceiver(bluetoothBroadcastReceiver, intentFilter);
    }


    /**
     * 显示蓝牙图标
     */
    protected void showBottomUI() {
        if (DataManager.Companion.getInstance().getMainStyle() == 3) {
//            setImage(R.id.ivBluetooth, BluetoothOrder.getInstance().isConnect() ?
//                    R.drawable.app_bluetooth_on_xm : R.drawable.app_bluetooth_off_xm);
        } else {
//            setImage(R.id.ivBluetooth, BluetoothOrder.getInstance().isConnect() ?
//                    R.drawable.app_bluetooth_on : R.drawable.app_bluetooth_off);
            try {
                if(Bluetooth.getInstance().isBluetoothOpened()){
                    setImage(R.id.iv_bluetooth, BluetoothOrder.getInstance().isConnect() ?
                            R.drawable.img_main_bluetooth_connect : R.drawable.img_main_bluetooth);
                }else {
                    setImage(R.id.iv_bluetooth, R.drawable.img_main_bluetooth_back);
                }

            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    /**
     * 显示用户信息
     */
//    public void showUserInfo() {
//        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
//        if (myInfo == null) {
//            setViewVisible(R.id.tvNotLogin);
//            setViewGone(R.id.ivAvatar, R.id.tvUseName);
//            return;
//        }
//        setViewGone(R.id.tvNotLogin);
//        setViewVisible(R.id.ivAvatar, R.id.tvUseName);
//        setText(R.id.tvUseName, myInfo.getNickname());
//        BaseUtils.StaticParams.loadImage(getApplicationContext(), R.drawable.app_not_login, myInfo.getHeadimg(), findViewById(R.id.ivAvatar));
//    }

    public void init() {
        mIsMainActivity = true;
        setViewsOnClickListener(R.id.tvNotLogin, R.id.tvUseName, R.id.ivAvatar, R.id.ivSetting, R.id.llStart,
                R.id.ivBluetooth, R.id.ivDisplay,R.id.ivHome);
        setTextTypeFace(R.id.tvSlope, R.id.tvDistance, R.id.tvSpeed);
        initView();
        startTimer();

//        if(DeviceTypeUtils.connectDeviceType() == 0){
//            System.out.println("ddddddddddddddddddddddd   isRun 444 :  " + BluetoothOrder.getInstance().isRun());
//            showStartBtn(BluetoothOrder.getInstance().isRun());
//            resetInfo(BluetoothOrder.getInstance().getCurrentInfo());
//        }else {
//            showStartBtn(SerialPortManager.getInstance().isRun());
//            resetInfo(SerialPortManager.getInstance().getCurrentInfo());
//        }
        System.out.println("ddddddddddddddddddddddd   isRun 444 :  " + MotionDataUtils.getInstance().isRun());
        showStartBtn(MotionDataUtils.getInstance().isRun());
        resetInfo(MotionDataUtils.getInstance().getCurrentInfo());
//        if (SerialPortManager.mCurrentDeviceType == DeviceType.CAR_WATCH) {
//            setText(R.id.tvSlopTitle, R.string.app_resistance);
//            setText(R.id.tvSpeedTitle, R.string.app_pace_500m);
//        }

        getPresenter().getAdvert();


        ConstraintLayout viewById = findViewById(R.id.rl_home);
        LayoutTouchListenerUtils.getInstance().setLayoutTouchListener(getApplicationContext(),viewById);//四个边边滑动监听
//        Channel initialize(Context srcContext, Looper srcLooper, ChannelListener listener)
//        System.out.println("ddddddddddddddddddddddd  当前亮度 ："+ SystemUtils.getInstance().getBrightness(getContentResolver()));
        RunningAppUtils.getInstance().init(getContext());


        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        toFragment(new HomeJyFragment());

//        if(DataManager.Companion.getInstance().getMainStyle() == ThemeUtils.THEME_DRAGON_BOAT_FESTIVAL){
//            toFragment(new HomeDWFragment());
//        }else if(DataManager.Companion.getInstance().getMainStyle() == ThemeUtils.THEME_FIRE_PROTECTION){
//            toFragment(new HomeXFFragment());
//        }else if(DataManager.Companion.getInstance().getMainStyle() == ThemeUtils.THEME_PINK){
//            toFragment(new HomePinkFragment());
//        }else if(DataManager.Companion.getInstance().getMainStyle() == ThemeUtils.THEME_LANDSCAPE){
//            toFragment(new HomeSceneryFragment());
//        }else {
//            toFragment(new HomeNewFragment());
//        }

//        CPUViewUtils.getInstance().initView(getContext());

        showCpu();
        Utils.initRegion(tvArea, tvLanguage,tvUnit);
    }

    public void initView(){
        viewPager = findViewById(R.id.viewPager);
        llHome = findViewById(R.id.ll_home);
        clHome = findViewById(R.id.cl_home);
        tvHome = findViewById(R.id.tv_home);
        ivHome = findViewById(R.id.iv_home);
        llSportsCenter = findViewById(R.id.ll_sports_center);
        clSportsCenter = findViewById(R.id.cl_sports_center);
        tvllSportsCenter = findViewById(R.id.tv_sports_center);
        ivllSportsCenter = findViewById(R.id.iv_sports_center);
        llVideoCourse = findViewById(R.id.ll_video_course);
        clVideoCourse = findViewById(R.id.cl_video_course);
        tvVideoCourse = findViewById(R.id.tv_video_course);
        ivVideoCourse = findViewById(R.id.iv_video_course);
        llEntertainment = findViewById(R.id.ll_entertainment);
        clEntertainment = findViewById(R.id.cl_entertainment);
        tvEntertainment = findViewById(R.id.tv_entertainment);
        ivEntertainment = findViewById(R.id.iv_entertainment);
        llDataHub = findViewById(R.id.ll_data_hub);
        clDataHub = findViewById(R.id.cl_data_hub);
        tvDataHub = findViewById(R.id.tv_data_hub);
        ivDataHub = findViewById(R.id.iv_data_hub);
        llRetract = findViewById(R.id.ll_retract);
        clRetract = findViewById(R.id.cl_retract);
        ivRetract = findViewById(R.id.iv_retract);
        tvRetract = findViewById(R.id.tv_retract);
        tvHelp = findViewById(R.id.tv_help);
        tvSetting = findViewById(R.id.tv_setting);
        tvStartSports = findViewById(R.id.tv_start_sports);
        tvArea = findViewById(R.id.tv_area);
        tvLanguage = findViewById(R.id.tv_language);
        tvUnit = findViewById(R.id.tv_unit);
        clSetItem = findViewById(R.id.cl_set_item);
        llArea = findViewById(R.id.ll_area);

        llHome.setOnClickListener(this);
        llSportsCenter.setOnClickListener(this);
        llVideoCourse.setOnClickListener(this);
        llEntertainment.setOnClickListener(this);
        llDataHub.setOnClickListener(this);
        llRetract.setOnClickListener(this);
        clSetItem.setOnClickListener(this);
        tvStartSports.setOnClickListener(this);
        tvSetting.setOnClickListener(this);
        llArea.setOnClickListener(this);

        mCurrentItem = 0;
        if(textViews == null){
            textViews = new ArrayList<>();
        }else {
            textViews.clear();
        }
        textViews.add(tvHome);
        textViews.add(tvllSportsCenter);
        textViews.add(tvVideoCourse);
        textViews.add(tvEntertainment);
        textViews.add(tvDataHub);
        textViews.add(tvRetract);

        if(imageViews == null){
            imageViews = new ArrayList<>();
        }else {
            imageViews.clear();
        }
        imageViews.add(ivHome);
        imageViews.add(ivllSportsCenter);
        imageViews.add(ivVideoCourse);
        imageViews.add(ivEntertainment);
        imageViews.add(ivDataHub);
        imageViews.add(ivRetract);

        if(clAnimationViews == null){
            clAnimationViews = new ArrayList<>();
        }else {
            clAnimationViews.clear();
        }
        clAnimationViews.add(clHome);
        clAnimationViews.add(clSportsCenter);
        clAnimationViews.add(clVideoCourse);
        clAnimationViews.add(clEntertainment);
        clAnimationViews.add(clDataHub);
        clAnimationViews.add(clRetract);

        if(clViews == null){
            clViews = new ArrayList<>();
        }else {
            clViews.clear();
        }
        clViews.add(clHome);
        clViews.add(clSportsCenter);
        clViews.add(clVideoCourse);
        clViews.add(clEntertainment);
        clViews.add(clDataHub);

//        mFragments = new ArrayList<>();
//        mFragments.add(HomeJyFragment.getInstance(0));
//        mFragments.add(SportsCenterFragment.getInstance(1));
//        mFragments.add(HomeJyFragment.getInstance(2));
//        mFragments.add(HomeJyFragment.getInstance(3));
//        mFragments.add(HomeJyFragment.getInstance(4));

//        viewPager.setOffscreenPageLimit(0);
//        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
//            @NonNull
//            @Override
//            public Fragment getItem(int position) {
//                return mFragments.get(position);
//            }
//
//            @Override
//            public int getCount() {
//                return mFragments.size();
//            }
//
//        });
//        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                mCurrentItem = position;
//                if(mCurrentItem == 0){
//                    tvStartSports.setVisibility(View.VISIBLE);
//                }else {
//                    tvStartSports.setVisibility(View.GONE);
//                }
//                resetBtn();
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
//        viewPager.setCurrentItem(mCurrentItem);
        resetBtn();
    }

    private void resetBtn() {
        if(mCurrentItem == 0){
//            tvStartSports.setVisibility(View.VISIBLE);
            startPlayAnimationShow();
        }else {
//            tvStartSports.setVisibility(View.GONE);
            startPlayAnimationExit();
        }
        for (int i = 0; i < clViews.size(); ++i) {
            if (i == mCurrentItem) {
                clViews.get(i).setBackgroundResource(R.drawable.shape_gradient_c5a070_00_c5a070_270);
            } else {
                clViews.get(i).setBackgroundResource(com.common.lib.R.color.transparent);
            }
        }
    }
    List<AnimatorSet> buttonAnimatorSets = new ArrayList<>();
    boolean isButton = true;
    public void initAnimation(){
        if(buttonAnimatorSets != null && buttonAnimatorSets.size()>0){
            buttonAnimatorSets.clear();
        }
        for (int i = 0;i< textViews.size();i++){
            int width = clAnimationViews.get(i).getWidth();
            int widthText = textViews.get(i).getWidth();
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageViews.get(i), "translationX", 0f, (width/2)-17);
            objectAnimator.setDuration(500);
            ObjectAnimator animResizeX = ObjectAnimator.ofFloat(textViews.get(i), "translationX", 0f, -width);
            animResizeX.setDuration(500);
            ObjectAnimator animResizeY = ObjectAnimator.ofFloat(clAnimationViews.get(i), "scaleX", 1f, 0f);
            animResizeY.setDuration(500);
            AnimatorSet buttonAnimatorSet = new AnimatorSet();
            buttonAnimatorSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isButton = false;
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            buttonAnimatorSet.playTogether(objectAnimator, animResizeX, animResizeY);//.after(rotationXAnimator)
            buttonAnimatorSets.add(buttonAnimatorSet);
        }
        for (AnimatorSet animatorSet : buttonAnimatorSets){
            animatorSet.start();
        }
//        buttonAnimatorSet.start();
    }
    public void endAnimation(){
        if(buttonAnimatorSets != null && buttonAnimatorSets.size()>0){
            buttonAnimatorSets.clear();
        }
        for (int i = 0;i< textViews.size();i++){
            int width = clAnimationViews.get(i).getWidth();
            int widthText = textViews.get(i).getWidth();
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageViews.get(i), "translationX", (width/2)-17, 0f);
            objectAnimator.setDuration(500);
            ObjectAnimator animResizeX = ObjectAnimator.ofFloat(textViews.get(i), "translationX", -width, 0);
            animResizeX.setDuration(500);
            ObjectAnimator animResizeY = ObjectAnimator.ofFloat(clAnimationViews.get(i), "scaleX", 0f, 1f);
            animResizeY.setDuration(500);
            AnimatorSet buttonAnimatorSet = new AnimatorSet();
            buttonAnimatorSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isButton = true;
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            buttonAnimatorSet.playTogether(objectAnimator, animResizeY,animResizeX);//.after(rotationXAnimator)
            buttonAnimatorSets.add(buttonAnimatorSet);
        }
        for (AnimatorSet animatorSet : buttonAnimatorSets){
            animatorSet.start();
        }
//        buttonAnimatorSet.start();
    }

    public void startPlayAnimationShow(){
        int visibility = tvStartSports.getVisibility();
        if(View.GONE == visibility){
            int width = tvStartSports.getWidth();
            ObjectAnimator animResizeX = ObjectAnimator.ofFloat(tvStartSports, "translationX", (width+108), 0);
            ObjectAnimator animator = ObjectAnimator.ofFloat(tvStartSports, "alpha", 0.0f, 1.0f);
            animResizeX.setDuration(500);
            animator.setDuration(500);
            AnimatorSet buttonAnimatorSet = new AnimatorSet();
            buttonAnimatorSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    tvStartSports.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isStartPlay = false;

                    buttonAnimatorSet.cancel();
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    buttonAnimatorSet.cancel();
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            buttonAnimatorSet.playTogether(animResizeX,animator);//.after(rotationXAnimator)
            buttonAnimatorSet.start();
        }
    }

    public void startPlayAnimationExit(){
        int visibility = tvStartSports.getVisibility();
        if(View.VISIBLE == visibility){
            int width = tvStartSports.getWidth();
            ObjectAnimator animResizeX = ObjectAnimator.ofFloat(tvStartSports, "translationX", 0, (width+108));
            ObjectAnimator animator = ObjectAnimator.ofFloat(tvStartSports, "alpha", 1.0f, 0.0f);
            animResizeX.setDuration(500);
            animator.setDuration(500);
            AnimatorSet buttonAnimatorSet = new AnimatorSet();
            buttonAnimatorSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isStartPlay = true;
                    tvStartSports.setVisibility(View.GONE);
                    buttonAnimatorSet.cancel();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            buttonAnimatorSet.playTogether(animResizeX,animator);//.after(rotationXAnimator)
            buttonAnimatorSet.start();
        }
    }



    public void showCpu(){
//        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

// 获取 Debug.MemInfo 对象
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int screenWidth = displayMetrics.widthPixels; // 屏幕宽度
        int screenHeight = displayMetrics.heightPixels; // 屏幕高度

        float density = displayMetrics.density; // 屏幕密度
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   screenWidth : "+screenWidth+"   screenHeight : "+screenHeight+"   density : "+density);

//        Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
//        Debug.getMemoryInfo(memoryInfo);
////        int totalPss = memoryInfo.getTotalPss();
//        int dalvikPss = memoryInfo.dalvikPss;
//        int nativePss = memoryInfo.nativePss;
//        int otherPss = memoryInfo.otherPss;
//        int totalPss = dalvikPss + nativePss + otherPss;
//        int cpuRate = totalPss / 1024; // CPU 使用率
//
//        DecimalFormat df = new DecimalFormat("#0.00");
//        mHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                double cpu = Double.parseDouble(df.format(Double.parseDouble(getCPURate()) * 100));
////                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   cpu : "+cpu);
//                String init = MemoryInfoUtils.getInstance().init(getApplicationContext());
//                CPUViewUtils.getInstance().setInfo(String.valueOf(cpu)+"%,内存:"+init);
//                mHandler.postDelayed(this,1000);
//            }
//        });



    }

    /**
     * ^ 表示匹配行的开头。
     * cpu 匹配 "cpu" 这个单词。
     * \\s+ 匹配一个或多个空格字符。
     * (\\d+\\s+){9} 匹配由一个或多个数字加上一个或多个空格字符组成的序列，重复9次。
     * \\d+ 匹配一个或多个数字。
     * $ 匹配行的结尾。 因此，整个正则表达式可以匹配以 "cpu" 开头，后面跟着10个由空格分隔的数字的行。
     */
    public static String getCPURate() {
        String path = "/proc/stat";// 系统CPU信息文件
        long Totaljiffies[] = new long[2];
        long totalIdle[] = new long[2];
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        Pattern pattern = Pattern.compile("^cpu\\s+(\\d+\\s+){9}\\d+$", Pattern.MULTILINE);
        //正则表达式，只获取第一行
        for (int i = 0; i < 2; i++) {  //每一次调用分为两次获取 方便求差
            Totaljiffies[i] = 0;
            totalIdle[i] = 0;
            try {
                fileReader = new FileReader(path);
                bufferedReader = new BufferedReader(fileReader, 8192);
                String str;
                while ((str = bufferedReader.readLine()) != null) {  //读取stat信息
                    if (str.toLowerCase().startsWith("cpu")) {//以cpu开头的
                        Matcher matcher = pattern.matcher(str);//直接获取第一行cpu开头的数据
                        // 不需要cpu0-7的，那样的话还得多几步运算
                        while (matcher.find()) {
                            String[] values = extractValues(matcher.group());
                            Totaljiffies[i] = sumValues(values);
                            totalIdle[i] = Long.parseLong(values[3]);
                        }
                    }
                    if(i==0){//第一次获取后进行延时等待系统更新信息
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        double rate = 0;
        if (Totaljiffies[1] > Totaljiffies[0] ) {//正常情况下第二次总的jiffies一定比第一次获得的数据大
            rate = 1.0 * ((Totaljiffies[1] - totalIdle[1]) - (Totaljiffies[0] - totalIdle[0]))
                    / (Totaljiffies[1] - Totaljiffies[0]);
        }
        return String.valueOf(rate);
    }
    /**
     * 头行去掉cpu，合并成String[]数组
     * @param input
     * @return
     */
    public static String[] extractValues(String input) {
        String[] parts = input.split("\\s+");
        String[] values = new String[parts.length - 1]; // 去掉 "cpu"，所以长度减一

        System.arraycopy(parts, 1, values, 0, parts.length - 1);
        return values;
    }
    /**
     * 求数组和
     * @param input
     * @return
     */
    public static Long sumValues(String input[]) {
        Long sum = Long.valueOf(0);
        for (String value : input) {
            sum += Integer.parseInt(value);
        }
        return sum;
    }



    public void toFragment(Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.slide_fragment_in,R.anim.slide_fragment_out);
        ft.replace(R.id.fl, fragment);
        ft.commit();
    }


    @NonNull
    @Override
    protected MainContract.Presenter onCreatePresenter() {
        return new MainPresenter(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivSound:
                Bundle bundle = new Bundle();
//                bundle.putInt(Constants.BUNDLE_EXTRA, 0);
//                openActivity(SoundActivity.class, bundle);

                new SoundPopupWindow(this).show();

                break;
            case R.id.ivBluetooth:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, 1);
                openActivity(SettingActivity.class, bundle);
                break;
            case R.id.ivHome:
                if(isMainActivity()){
                    getSupportFragmentManager()
                            .popBackStack();
                }else {
                    toHomeActivity();
                }
                break;
            case R.id.tvNotLogin:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                openActivity(LoginActivity.class);
                break;
            case R.id.tvUseName:
            case R.id.ivAvatar:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                openActivity(UserProfileActivity.class);
                break;
            case R.id.ivDisplay:
//                try {
//                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.rockchip.wfd");
//                    startActivity(intent);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                if(DeviceTypeUtils.getInstance().isInstallApp(getContext(),DeviceTypeUtils.LEBO)){
                    DeviceTypeUtils.getInstance().openApp(getContext(),DeviceTypeUtils.LEBO);
                }else {
                    ToastUtils.getInstance().show(getContext(),getString(R.string.app_toast_hint_3));
                }


//                bundle = new Bundle();
//                bundle.putInt(Constants.BUNDLE_EXTRA, 2);
//                openActivity(SettingActivity.class, bundle);
                break;
            case R.id.ivSetting:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                openActivity(SettingActivity.class);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                break;
            case R.id.llStart:
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
//                if (!DataManager.Companion.getInstance().isLogin()) {
//                    showToast(R.string.app_please_login_first);
//                    openActivity(LoginActivity.class);
//                    return;
//                }
                if (MotionDataUtils.getInstance().isRun()) {//判断是否有在运行
                    stopDevice();
                } else {
                    Log.e("aaaaaaaaaaaaa", "start run");
                    System.out.println("ddddddddddddddddddddddd   蓝牙是否连接 : "+BluetoothOrder.getInstance().isConnect());
                    if(DeviceTypeUtils.connectDeviceType() == 0){
                        System.out.println("ddddddddddddddddddddddd   蓝牙通知设备开始");
                        if(DeviceTypeUtils.getInstance().isTreadmill()){
                            BluetoothOrder.getInstance().startTreadmill();
                        }else {
                            BluetoothOrder.getInstance().startPlay();
                        }

                    }else {
                        System.out.println("ddddddddddddddddddddddd   串口通知设备开始");
                        SerialPortManager.getInstance().startRun();
                    }
                    if (mIsMainActivity && DataManager.Companion.getInstance().isLogin()) {
                        bundle = new Bundle();
                        bundle.putInt(Constants.BUNDLE_EXTRA, 1);
                        openActivity(FreeMovementActivity.class, bundle);
                    }
                }

                break;
            case R.id.ll_home:
                mCurrentItem = 0;
//                viewPager.setCurrentItem(0);
                toFragment(new HomeJyFragment());
                resetBtn();
                break;
            case R.id.ll_sports_center:
                mCurrentItem = 1;
//                viewPager.setCurrentItem(1);
                toFragment(new SportsCenterFragment());
                resetBtn();
                break;
            case R.id.ll_video_course:
                mCurrentItem = 2;
//                viewPager.setCurrentItem(2);
                toFragment(VideoListFragment.getInstance(0,1));
                resetBtn();
                break;
            case R.id.ll_entertainment:
                mCurrentItem = 3;
//                viewPager.setCurrentItem(3);
//                openActivity(ApplicationActivity.class);
                toFragment(new ApplicationFragment());
                resetBtn();
                break;
            case R.id.ll_data_hub:
                mCurrentItem = 4;
//                viewPager.setCurrentItem(4);
                toFragment(new SportRecordFragment());
                resetBtn();
                break;
            case R.id.ll_retract:
                if(isButton){
                    initAnimation();
                }else {
                    endAnimation();
                }

                break;
            case R.id.tv_start_sports:
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    ToastUtils.getInstance().show(getContext(),getString(R.string.app_device_connect));
                    return;
                }
                Utils.startSports(getContext(),false);
                break;
            case R.id.tv_setting:
                openActivity(SettingNewActivity.class);
                break;
            case R.id.cl_set_item:
                SimpleSettingViewUtils.getInstance().initView(getContext(),this);
                break;
            case R.id.ll_area:
                Intent intent = new Intent(this, SettingNewActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, 1); // 直接打开通用设置界面
                startActivity(intent);
                break;

        }
    }

    public void stopDevice(){
        if(!(SerialPortManager.getInstance().isConnected() || BluetoothOrder.getInstance().isConnect())){
            System.out.println("ddddddddddddddddddddddd   未连接设备");
            return;
        }
        if(DeviceTypeUtils.connectDeviceType() == 0){//判断连接类型
            BluetoothOrder.getInstance().closeRxJavaClone();
            BluetoothOrder.getInstance().closeTreadmillStateDisposable();
            if(EquipmentInfoUtils.getInstance().isPause()){
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备暂停");
                if(DeviceTypeUtils.getInstance().isTreadmill()){
                    BluetoothOrder.getInstance().pauseTreadmill();
                }else {
                    BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_PAUSE);
                }

            }else {
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备停止");
                if(DeviceTypeUtils.getInstance().isTreadmill()){
                    BluetoothOrder.getInstance().stopTreadmill();
                } else {
                    BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_STOP);
                }

            }
        }else {
            System.out.println("ddddddddddddddddddddddd   串口通知设备停止");
            SerialPortManager.getInstance().stopRun();
        }
    }

    boolean isShowCount = true;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if (map.containsKey(EventBusEvent.START_RUN)) {
            int count = (int) map.get(EventBusEvent.START_RUN);
            System.out.println(TAG+" ddddddddddddddddddddddd  countdown : "+count);
            if(isShowCount){
                isShowCount = false;
                System.out.println(TAG+" ddddddddddddddddddddddd  isShowCount : "+isShowCount);
                if(count > 0){
                    CountDownViewUtils.getInstance().initView(getContext(),count);
                }else{
                    CountDownViewUtils.getInstance().initView(getContext(),3);
                }
                BackButtonViewUtils.getInstance().initPause();
            }
        } else if (map.containsKey(EventBusEvent.IS_SHOW_COUNT)) {
            isShowCount = true;
            if(SystemUtils.isForeground(this,getPackageName())){
                openActivity(FreeMovementNewActivity.class);
            }
        } else if (map.containsKey(EventBusEvent.RUNNING)) {
//            showStartBtn(true);
            BackButtonViewUtils.getInstance().initPause();
        } else if ( map.containsKey(EventBusEvent.STOP_RUN)) {
            System.out.println("BluetoothOrder -------------> ddddddddddddddddddddddd  STOP_RUN : 3");
            isShowCount = true;
//            CountDownViewUtils.getInstance().setIsVideo(false);
            showStartBtn(false);
            if(SystemUtils.isForeground(getContext(),getPackageName())){
                SportsStatusBarViewUtils.getInstance().goneLayout();
                SportsStatusBarViewUtils.getInstance().initEnabled(true);
                ApkListViewUtils.getInstance().goneButton();
            }else {
                ShowSpeedViewUtils.getInstance().recoverAnimation();
                SportsStatusBarViewUtils.getInstance().showStartBtn(false);
                SportsStatusBarViewUtils.getInstance().initView(getApplicationContext());
            }
            BackButtonViewUtils.getInstance().goneButton();
            BackButtonViewUtils.getInstance().initPause();
            DataManager.Companion.getInstance().saveSetTarget(null);
            ShowSpeedViewUtils.getInstance().initInfo();
            SerialPortManager.getInstance().setRunStatus(SportStatus.STOP);
            SportsStatusBarViewUtils.getInstance().stopInitView();
            SportsDataUtils.getInstance().uploadSportInfo(false);
            MotionDataUtils.getInstance().closeCurrentInfo();//清除上次运动数据

//            currentInfo.time = 0;
//            resetInfo(currentInfo);
//            stopDevice();
        }else if ( map.containsKey(EventBusEvent.PAUSE_RUN)){
            System.out.println("BluetoothOrder -------------> ddddddddddddddddddddddd  PAUSE_RUN : 2");
            isShowCount = true;
            showStartBtn(false);
            SportsStatusBarViewUtils.getInstance().initEnabled(true);
            SerialPortManager.CurrentInfo currentInfo = MotionDataUtils.getInstance().getCurrentInfo();
            SerialPortManager.getInstance().setRunStatus(SportStatus.PAUSE);
            BackButtonViewUtils.getInstance().initPause();
//            SportsDataUtils.getInstance().uploadSportInfo(false);
//            SportsStatusBarViewUtils.getInstance().pauseInitView();
//            ShowSpeedViewUtils.getInstance().initInfo();
            ApkListViewUtils.getInstance().goneButton();
//            currentInfo.time = 0;
            resetInfo(currentInfo);

        } else if (map.containsKey(EventBusEvent.DEVICE_DATA)) {
            System.out.println("BluetoothOrder -------------> ddddddddddddddddddddddd  CurrentInfo : "+ GsonUtils.toJson((SerialPortManager.CurrentInfo) map.get(EventBusEvent.DEVICE_DATA)));
            resetInfo((SerialPortManager.CurrentInfo) map.get(EventBusEvent.DEVICE_DATA));
        } else if (map.containsKey(EventBusEvent.BLUETOOTH_CHANGE)) {
//            setImage(R.id.ivBluetooth, (boolean) map.get(EventBusEvent.BLUETOOTH_CHANGE) ?
//                    R.drawable.app_bluetooth_on : R.drawable.app_bluetooth_off);
            showBottomUI();
        } else if (map.containsKey(EventBusEvent.WIFI_CHANGE)) {
            //TODO 临时try，界面来不及统一
            try {
                setImage(R.id.iv_wifi, WifiSupport.isWifiConnected(getContext()) ? R.drawable.img_main_wifi:
                        R.drawable.img_main_wifi_back);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(map.containsKey(EventBusEvent.EQUIPMENT_STATE)){//设备状态
//            SerialPortManager.CurrentInfo currentInfo = (SerialPortManager.CurrentInfo) map.get(EventBusEvent.EQUIPMENT_STATE);
            SerialPortManager.CurrentInfo currentInfo = MotionDataUtils.getInstance().getCurrentInfo();
            resetInfo(currentInfo);

        }else if(map.containsKey(EventBusEvent.SPORTS_DATA)){
//            SerialPortManager.CurrentInfo currentInfo = (SerialPortManager.CurrentInfo) map.get(EventBusEvent.SPORTS_DATA);
            SerialPortManager.CurrentInfo currentInfo = MotionDataUtils.getInstance().getCurrentInfo();
            resetInfo(currentInfo);
        } else if (map.containsKey(EventBusEvent.RESTART_APP)) {
            finishAllActivity();
            openActivity(MainActivity.class);
        }else if(map.containsKey(EventBusEvent.REFRESH_BLUETOOTH)){
            showBottomUI();
        }else if(map.containsKey(EventBusEvent.VOICE_CHANGE)){
            int i = (int) map.get(EventBusEvent.VOICE_CHANGE);
            if(i <= 0){
                setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_off);

            }else {
                setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_max);
            }
        }else if(map.containsKey(EventBusEvent.BRIGHTNES_CHANGE)){
            int brightnes = (int) map.get(EventBusEvent.BRIGHTNES_CHANGE);
            //设置亮度
//            SystemUtils.changeAppBrightness(this,brightnes);
            Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, brightnes);
        }else if(map.containsKey(EventBusEvent.SET_TARGET)){
            ArrayList<Integer> o = (ArrayList<Integer>) map.get(EventBusEvent.SET_TARGET);
            targetType = o.get(0);
            targetNum = o.get(1);
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  targetType : "+targetType+"   targetNum  : "+targetNum);
            SportsStatusBarViewUtils.getInstance().setTarget(targetType,targetNum);
        }else if(map.containsKey(EventBusEvent.SET_HOME_OR_SET)){
            boolean b = (boolean) map.get(EventBusEvent.SET_HOME_OR_SET);
            SportsStatusBarViewUtils.getInstance().setHomeView(b);
        }else if(map.containsKey(EventBusEvent.IS_SHOW_APP)){
            boolean b = (boolean) map.get(EventBusEvent.IS_SHOW_APP);
            SportsStatusBarViewUtils.getInstance().setIsShowApp(b);
        }else if (map.containsKey(EventBusEvent.TO_MAIN)) {
            openActivity(MainActivity.class);
        }else if (map.containsKey(EventBusEvent.SPORTS_REPORT)) {
            int mRid = (int) map.get(EventBusEvent.SPORTS_REPORT);
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   运动报告  mRid  :  "+mRid);
            Bundle bundle = new Bundle();
            bundle.putInt(Constants.BUNDLE_EXTRA, mRid);
            openActivity(SportReportActivity.class,bundle);
        }else if(map.containsKey(EventBusEvent.REFRESH_WIFI)){
            //TODO 临时try，界面来不及统一
            try {
                setImage(R.id.iv_wifi, WifiSupport.isWifiConnected(getContext()) ? R.drawable.img_main_wifi:
                        R.drawable.img_main_wifi_back);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(map.containsKey(EventBusEvent.SAFETY_LOCK)){
            boolean b = (boolean) map.get(EventBusEvent.SAFETY_LOCK);
            if(b){
                if(!SafetyLockViewUtils.getInstance().isShow()){
                    SafetyLockViewUtils.getInstance().initView(getApplicationContext());
                }
//                DialogViewUtils.getInstance().initView(getApplicationContext(),false,DialogViewUtils.SAFETY_LOCK);
            }else {
                SafetyLockViewUtils.getInstance().goneLayout();
//                DialogViewUtils.getInstance().goneLayout();
            }
        }else {
            super.onReceive(map);
        }
    }

    public void initSound(){
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if(currentVolume <= 0){
            setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_off);

        }else {
            setImage(R.id.iv_sound,R.drawable.img_simple_set_sound_max);
        }
    }
    public void resetInfo(SerialPortManager.CurrentInfo info) {
        float kcal = 0;
        String speed = null;
        String timeStr = null;

        if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)
                ||MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING)
                ||MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ELLIPTICAL_MACHINE)){
//                setText(R.id.tvSlope, String.valueOf(info.slop));
//                setText(R.id.tvSpeed, Utils.getNewFloat(info.speed*0.1f));
            if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
                speed = Utils.getNewFloat(info.speed / 10f);
            }else {
                speed = Utils.getNewFloat(info.speed / 100f);
            }

            kcal = info.kcal/10f;
        }else if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
//                setText(R.id.tvSlope, String.valueOf(info.slop));
            String text;
            if (info.speed == 0) {
                text = "00:00";
            } else {
                int time = (int) (1800 / (info.speed * 0.01) + 0.5);  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
                int hour = time / 3600;
                int minute = (time / 60) % 60;
                int second = time % 60;
                if (hour > 0) {
                    text = BaseUtils.StaticParams.getNewText(hour) + ":"
                            + BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                } else {
                    text = BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                }
            }
//                setText(R.id.tvSpeed, text);
            kcal = info.kcal/10f;
            speed = Utils.getNewFloat(info.speed / 100f);
        }
        SportsStatusBarViewUtils.getInstance().showStartBtn(MotionDataUtils.getInstance().isRun());

        int hour = info.time / 3600;
        int minute = (info.time / 60) % 60;
        int second = info.time % 60;
        if (hour > 0) {
            timeStr =  BaseUtils.StaticParams.getNewText(hour) + ":"
                    + BaseUtils.StaticParams.getNewText(minute) + ":"
                    + BaseUtils.StaticParams.getNewText(second);
        } else {
            timeStr = BaseUtils.StaticParams.getNewText(minute) + ":"
                    + BaseUtils.StaticParams.getNewText(second);

        }
        ShowSpeedViewUtils.getInstance().setInfo(info.heart+"",speed,
                Utils.getNewFloat2(info.distance / 1000f),timeStr,Utils.getNewFloat(kcal));
        BackButtonViewUtils.getInstance().setInfo(info);

        if(targetType == SetTargetViewUtils.TYPE_TIME){
            if(info.time >= (targetNum*60)){
                SetTargetViewUtils.getInstance().showToast(getContext(),isShowToast);
                isShowToast = false;
                targetNum = 0;
                targetType = 0;
            }
        }else if(targetType == SetTargetViewUtils.TYPE_DISTANCE){
            if(info.distance >= (targetNum*1000f)){
                SetTargetViewUtils.getInstance().showToast(getContext(),isShowToast);
                isShowToast = false;
                targetNum = 0;
                targetType = 0;
            }

        }else if(targetType == SetTargetViewUtils.TYPE_KCAL){
            if(kcal >= targetNum){
                SetTargetViewUtils.getInstance().showToast(getContext(),isShowToast);
                isShowToast = false;
                targetNum = 0;
                targetType = 0;
            }
        }
//        setText(R.id.tvDistance, Utils.getNewFloat2(info.distance / 1000f));
        SportsDataUtils.getInstance().setSportsData(info);
        SportsStatusBarViewUtils.getInstance().setInfo(info);
//        ShowSpeeldAndSlopUtils.getInstance().setInfo(info);
    }

    public void showStartBtn(boolean isRun) {
//        LinearLayout llStart = findViewById(R.id.llStart);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaa   isRun  :  "+isRun);
        SportsStatusBarViewUtils.getInstance().showStartBtn(isRun);

    }

    /**
     * 显示屏保的倒计时
     */
    public void startTimer() {   //做一个全局倒计时显示时间
        if (mDisposableCountDown != null) {
            mDisposableCountDown.dispose();
        }
        mDisposableCountDown = Observable.intervalRange(1, Long.MAX_VALUE, 500, 1, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put(EventBusEvent.TIME_CHANGE, "");
//                        EventBus.getDefault().post(map);  //时间变化通知其他页面
                        int type = DataManager.Companion.getInstance().getScreenTime();
                        if (type == 0) {  //没有屏保
                            return;
                        }
                        long dTime = 0L;
                        switch (type) {
                            case 1:
                                dTime = 60 * 1000L;
                                break;
                            case 2:
                                dTime = 3 * 60 * 1000L;
                                break;
                            case 3:
                                dTime = 5 * 60 * 1000L;
                                break;
                            case 4:
                                dTime = 15 * 60 * 1000L;
                                break;
                            case 5:
                                dTime = 30 * 60 * 1000L;
                                break;
                        }

                        long lastTapTime = DataManager.Companion.getInstance().getTapTime();

                        if (lastTapTime > 0L && System.currentTimeMillis() - lastTapTime > dTime) {
                            DataManager.Companion.getInstance().saveTapTime(System.currentTimeMillis());
                            if(MotionDataUtils.getInstance().isRun()){
                                return;
                            }
                            openActivity(ScreenProtectActivity.class);
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
//                        resetDate();
                    }
                });
    }

    public void onDestroy() {
        super.onDestroy();
        if (mDisposableCountDown != null) {
            mDisposableCountDown.dispose();
        }

        unregisterReceiver(wifiBroadcastReceiver);
        unregisterReceiver(bluetoothBroadcastReceiver);
    }

    /**
     * 重置时间
     */
    public void resetDate() {
        Calendar now = Calendar.getInstance();
        Date date = new Date();


//        if (now.get(Calendar.AM_PM) == Calendar.AM) {
//            setText(R.id.tvCurrentTime, BaseUtils.StaticParams.getNewText(now.get(Calendar.HOUR_OF_DAY))
//                    + ":" + BaseUtils.StaticParams.getNewText(now.get(Calendar.MINUTE)) + " " + getString(R.string.app_am));
//        } else {
//            setText(R.id.tvCurrentTime, BaseUtils.StaticParams.getNewText(now.get(Calendar.HOUR_OF_DAY) - 12)
//                    + ":" + BaseUtils.StaticParams.getNewText(now.get(Calendar.MINUTE)) + " " + getString(R.string.app_pm));
//        }
//        int day = now.get(Calendar.DAY_OF_MONTH);
//        int weekDay = now.get(Calendar.DAY_OF_WEEK);
//        setText(R.id.tvDate, getString(getResources().getIdentifier("app_weekday_" + weekDay, "string", getPackageName())) + " " + BaseUtils.StaticParams.getNewText(day));
    }

    /**
     * 设置控件透明度
     * @param alpha
     * @param viewIds
     */
    public void setViewsAlpha(float alpha, int... viewIds) {
        for (int viewId : viewIds) {
            View view = findViewById(viewId);
            if (view == null) {
                continue;
            }
            view.setAlpha(alpha);
        }
    }

    @Override
    public boolean isMainActivity() {
        return true;
    }

    @Override
    public void getAdvertSuccess(ArrayList<BannerBean> list) {

    }

    @Override
    public void getVersionSuccess(VersionBean bean) {

    }

    @Override
    public void getVideoListSuccess(ProceduralTrainBean bean) {

    }
    public void setWifiImag(boolean isWifiConnected) {
        if (isWifiConnected){
            setImage(R.id.iv_wifi,R.drawable.img_main_wifi);
        }else {
            setImage(R.id.iv_wifi,R.drawable.img_main_wifi_back);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBroadcastReceive(Intent intent) {
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (state) {
                case WifiManager.WIFI_STATE_DISABLED: {
                    Log.d(TAG, "已经关闭");
//                    isWifiOpened = false;
                    break;
                }
                case WifiManager.WIFI_STATE_DISABLING: {
                    Log.d(TAG, "正在关闭");
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLED: {
                    Log.d(TAG, "已经打开");
//                    isWifiOpened = true;
//                    sortScaResult();
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLING: {
                    Log.d(TAG, "正在打开");
                    break;
                }
                case WifiManager.WIFI_STATE_UNKNOWN: {
                    Log.d(TAG, "未知状态");
                    break;
                }
            }
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
                Log.d(TAG, "wifi没连接上");

            } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                Log.d(TAG, "wifi连接上了");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getContext());
                //连接成功 跳转界面 传递ip地址
//                tvWlan.setText(connectedWifiInfo.getSSID().replace("\"", ""));
                setWifiImag(true);
                dismissProgressDialog();
            } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                Log.d(TAG, "wifi正在连接");
                WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getContext());

            }
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
//            isWifiChange = true;
        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            switch (state) {//TODO Setting文件里面代码，网络状态监听变化 断开、连接、密码错误的操作全在这里进行
                case ASSOCIATING://申请连接中
//                    mWasAssociating = true;
                    break;
                case ASSOCIATED:
//                    mWasAssociated = true;
                    break;
                case COMPLETED://连接成功后进入
//                    isExit = false;
//                    isWifiOpened = false;
                    WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(getContext());
                    //连接成功 跳转界面 传递ip地址
//                    tvWlan.setText(connectedWifiInfo.getSSID().replace("\"", ""));
                    setWifiImag(true);
                    dismissProgressDialog();
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(EventBusEvent.REFRESH_WIFI,0);
                    EventBus.getDefault().post(map);
                    break;
                case DISCONNECTED://断开连接后进入dormant判断是密码错误还是其他连接错误
                case DORMANT:
                    setWifiImag(false);
//                    tvWlan.setText(getString(R.string.app_not_connect));
//                    isWifiOpened = false;
//                    if (mWasAssociated || mWasHandshaking) {
//                        if (mConnectType != 0) {
//                            //解绑
//                            mConnectType = 0;
//                            WifiSupport.doDisconnectWifi("\"" + mConnectionWifi.getWifiName() + "\"", getActivity());
//                            sortScaResult();
//                            dismissProgressDialog();
//                            Intent i = new Intent(getActivity(), DialogActivity.class);
//                            i.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.SHOW_INPUT_WIFI_PSW_DIALOG);
//                            i.putExtra(Constants.BUNDLE_EXTRA_2, mConnectionWifi.getWifiName());
//                            mLauncher.launch(i);
//                            showToast(R.string.app_check_wifi_password);
//                        }
//                    }
                    break;
                case INTERFACE_DISABLED:
                case UNINITIALIZED:
                    break;
                case FOUR_WAY_HANDSHAKE://四次握手进入连接
                case GROUP_HANDSHAKE:
//                    mWasHandshaking = true;
                    break;
            }
        }
    }


}